package elsa.controller;

import com.github.pagehelper.PageHelper;
import elsa.bean.ScsTree;
import elsa.bean.ScsStatute;
import elsa.bootmapper.StatuteMapper;
import elsa.tools.Message;
import elsa.tools.MyResp;
import elsa.tools.UploadResp;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

@Controller
public class StatuteController {

    @Autowired
    private StatuteMapper statuteMapper;


    //查询树
    @CrossOrigin
    @RequestMapping(value = "/statute", method = RequestMethod.GET)
    @ResponseBody
    @RequiresPermissions("public")
    public List<ScsTree> findTree(){
        List<ScsTree> root = statuteMapper.findByPid("-1");  //获取根节点（获取的值存到list中）
        net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(buildTree(root));
        return buildTree(root);
    }
    private List<ScsTree> buildTree(List<ScsTree> root){
        for(int i=0;i<root.size();i++){
            List<ScsTree> children = statuteMapper.findByPid(root.get(i).getId()); //查询某节点的子节点（获取的是list）
            buildTree(children);
            root.get(i).setChildren(children);
        }
        return root;
    }

    //新增树节点
    @CrossOrigin
    @RequestMapping(value = "/statute/new", method = RequestMethod.PUT)
    @ResponseBody
    @RequiresPermissions(value = {"admin","head"},logical= Logical.OR)
    public String saveTree(@RequestBody ScsTree scsTree){
        if(scsTree.getId()!=null&&!statuteMapper.findById(scsTree.getId()).toString().equals("[]")){
            return "节点已存在!";
        }else if (scsTree.getId()==null){
            return "节点不存在!";
        }else if(scsTree.getPid()==null||statuteMapper.findById(scsTree.getPid()).toString().equals("[]")){
            return "父节点不存在!";
        }else if(scsTree.getName()==null){
            return "节点名称填写错误!";
        }else if(scsTree.getName().length()>30){
            return "节点名称字数应不超过30个字!";
        }else{
            statuteMapper.saveTree(scsTree);
            return "新增成功!";
        }
    }

    //更新树节点
    @CrossOrigin
    @RequestMapping(value = "/statute/update", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions(value = {"admin","head"},logical= Logical.OR)
    public String updateTree(@RequestBody ScsTree scsTree){
        String b;
        if(scsTree.getId()==null||statuteMapper.findById(scsTree.getId())==null){
            b = "节点不存在!";
        }else if(scsTree.getName()==null||scsTree.getName().equals("")||scsTree.getName().length()>40){
            b = "节点名称格式错误!";
        }else {
            statuteMapper.updateTree(scsTree);
            b = "更新成功!";
        }
        return b;
    }

    //删除树节点
    @CrossOrigin
    @RequestMapping(value = "/statute/delete/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    @RequiresPermissions(value = {"admin","head"},logical= Logical.OR)
    public String deleteTree(@PathVariable("id") String id){
        if(id!=null&&statuteMapper.findById(id)!=null){
            statuteMapper.deleteTree(id);
            return "删除成功!";
        }else if(id!=null&&id.equals("-1")){
            return "无法删除!";
        } else{
            return "节点不存在!";
        }
    }

    //查询法规
    @CrossOrigin
    @RequestMapping(value = "/statute/{parentid}", method = RequestMethod.GET)
    @ResponseBody
    @RequiresPermissions("public")
    public MyResp statuteAllList(@PathVariable("parentid") String parentid,
                                @RequestParam("pageIndex") Integer pageIndex,
                                @RequestParam("pageSize") Integer pageSize){
        if(pageIndex==null){
            pageIndex=1;
        }
        if(pageSize==null){
            pageSize=10;
        }
        if(parentid==null){
            parentid="";
        }
        PageHelper.startPage(pageIndex, pageSize);
        return MyResp.render(0,"获取成功",statuteMapper.findStatute(parentid),statuteMapper.findStatuteCount(parentid));
    }

    //新建法规/上传法规
    @CrossOrigin
    @RequestMapping(value = "/statute/new", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions(value = {"admin","head"},logical= Logical.OR)
    public UploadResp upload(@RequestParam("file") MultipartFile file, HttpServletRequest request){
        String classPath = this.getClass().getClassLoader().getResource("").getPath();
        String path = classPath.substring(0,classPath.indexOf("WEB-INF"))+"file/statute/";
        path=path.replaceAll("%20"," ");
        if (file.isEmpty()) {
            return UploadResp.render(0, "文件为空", "", "");
        }
        String statuteid = request.getParameter("statuteid");
        String parentid = request.getParameter("parentid");
        String fileName = file.getOriginalFilename();
        String uploader = request.getParameter("uploader");
        String filepath = path+parentid+"\\"+fileName;
        File dest = new File(filepath);
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }
        try{
            file.transferTo(dest);
            ScsStatute scsStatute = new ScsStatute();
            scsStatute.setStatuteid(statuteid);
            scsStatute.setParentid(parentid);
            scsStatute.setUploader(uploader);
            scsStatute.setStatutename(fileName.substring(0,fileName.lastIndexOf(".")));
            scsStatute.setStatuteurl("statute/"+parentid+"/"+fileName);
            scsStatute.setUploadtime(getNtime());
            statuteMapper.saveStatute(scsStatute);
            return UploadResp.render(0,"上传成功","statute/"+parentid+"/"+fileName, fileName);
        }catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return UploadResp.render(0, "上传失败", "", "");
    }

    //删除法规
    @CrossOrigin
    @RequestMapping(value = "/statute/delete/{statuteid}", method = RequestMethod.GET)
    @ResponseBody
    @RequiresPermissions(value = {"admin","head"},logical= Logical.OR)
    public Message deleteStatute(@PathVariable("statuteid") String statuteid){
        String b;
        String classPath = this.getClass().getClassLoader().getResource("").getPath();
        String thepath = classPath.substring(0,classPath.indexOf("WEB-INF"))+"file/";
        thepath=thepath.replaceAll("%20"," ");
        if(statuteMapper.findStatuteInfo(statuteid)==null){
            b = "法规不存在!";
        }else {
            String path = thepath+statuteMapper.findStatuteInfo(statuteid).getStatuteurl();
            File file = new File(path);
            if(file.exists()){
                file.delete();
            }
            statuteMapper.deleteStatute(statuteid);
            b = "删除成功!";
        }
        Message message = new Message(b);
        return message;
    }

    // 获取当前时间
    private Date getNtime(){
        Date date = new Date();
        return new Timestamp(date.getTime());
    }

}
